package com.cloudkinto.service.covershows.impl;

import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.entity.NewsInformationDo;
import com.cloudkinto.dao.NewsInformationDao;
import com.cloudkinto.service.covershows.NewsInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.covershows.vo.*;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.storage.StorageService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-09-27
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class NewsInformationServiceImpl extends ServiceImpl<NewsInformationDao, NewsInformationDo> implements NewsInformationService {
    @Autowired
    private NewsInformationDao dao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FileService fileService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private JpRegionService jpRegionService;
    @Autowired
    private MailSenderService mailSenderService;
    @Autowired
    private ThreadPoolTaskExecutor executor;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public void add(NewsInformationAddReq req, Long userId) {
        NewsInformationDo entityDo = new NewsInformationDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setBrowseCount(10000);
        entityDo.setCollectCount(10000);
        StringBuilder sb = new StringBuilder("");
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);

        fileService.uploadFile(req.getFileId());
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(NewsInformationDo entityDo, Long userId) {
        entityDo.setCreateTime(new Date());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(NewsInformationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public void update(NewsInformationUpdateReq req, Long userId) {
        NewsInformationDo entityDo = dao.selectById(req.getId());
        if (req.getFileId() != null) {
            fileService.deleteFile(entityDo.getFileId());
            fileService.uploadFile2(req.getFileId(), entityDo.getFileId());
        }
        BeanUtils.copyProperties(req, entityDo);
        StringBuilder sb = new StringBuilder("");
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(NewsInformationDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(NewsInformationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        return dao.deleteById(id);
    }


    @Override
    public NewsInformationDetailRes detail(Long id) {
        NewsInformationDo entityDo = dao.selectById(id);
        entityDo.setBrowseCount(entityDo.getBrowseCount() + 1);
        entityDo.setCollectCount(entityDo.getCollectCount() + 1);
        dao.updateById(entityDo);
        NewsInformationDetailRes res = new NewsInformationDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setBrowseCount("1w+");
        res.setCollectCount("1w+");
        res.setFileUrl(fileService.getFilePath(entityDo.getFileId()));
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<NewsInformationPageRes> getList(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = queryBuild(map);
        List<NewsInformationDo> list = this.list(wrapper);
        List<NewsInformationPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = queryBuild(map);
        IPage<NewsInformationDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<NewsInformationPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public SingleResult dataStatistics() {
        Integer fbaInputCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.FBA_INPUT_KEY);
        Integer jpSendOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.JP_SEND_OUT_KEY);
        Integer orderBackOutCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.ORDER_BACK_KEY);
        Integer storageAreaCount = (Integer) redisTemplate.opsForValue().get(GlobalConstants.STORAGE_AREA_KEY);

        if (fbaInputCount == null) {
            fbaInputCount = 0;
        }
        if (jpSendOutCount == null) {
            jpSendOutCount = 0;
        }
        if (orderBackOutCount == null) {
            orderBackOutCount = 0;
        }
        if (storageAreaCount == null) {
            storageAreaCount = 0;
        }

        Map map = new HashMap();
        map.put("fbaInputCount", fbaInputCount);
        map.put("jpSendOutCount", jpSendOutCount);
        map.put("orderBackOutCount", orderBackOutCount);
        map.put("storageAreaCount", storageAreaCount);
        return SingleResult.success(map);
    }

    @Override
    public SingleResult advice(AdviceReq req) {
        executor.execute(() -> {
            mailSenderService.sendEmail("您有顾客反馈意见:", "<br>公司名称:" +(StringUtils.isNotBlank( req.getNamex())? req.getNamex():"") +
                            "<br>公司性质:" + (StringUtils.isNotBlank(req.getTypeOfCompany()) ? req.getTypeOfCompany() : "") +
                            "<br>是否用过海外仓:" + (StringUtils.isNotBlank(req.getHaveOverseasWarehouse()) ? req.getHaveOverseasWarehouse() : "") +
                            "<br>人员规模:" + (StringUtils.isNotBlank(req.getPersonnel()) ? req.getPersonnel() : "") +
                            "<br>年出口金额:" + (StringUtils.isNotBlank(req.getExport()) ? req.getExport() : "")+"" +
                            "<br>年出口集装箱数:" + (StringUtils.isNotBlank(req.getNumberOfExportContainers()) ? req.getNumberOfExportContainers() : "") +
                            "<br>经营产品:" + (StringUtils.isNotBlank(req.getOperatingProductType()) ? req.getOperatingProductType() : "") +
                            "<br>联系人:" + (StringUtils.isNotBlank(req.getNamess()) ? req.getNamess() : req.getName()) +
                            "<br>电话:" + (StringUtils.isNotBlank(req.getPhoness()) ? req.getPhoness() : req.getTel()) +
                            "<br>邮箱:" + (StringUtils.isNotBlank(req.getEmail()) ? req.getEmail() : "") +
                            "<br>地址:" + (StringUtils.isNotBlank(req.getAddress()) ? req.getAddress() : "") +
                            "<br>微信:" + req.getWeixin(),
                    SysConstant.cloudkintEmail);
        });
        return null;
    }

//    @Override
//    public SingleResult storageList() {
//        return SingleResult.success(storageService.storageList());
//    }
//
//    @Override
//    public SingleResult jpRegionList() {
//        return SingleResult.success(jpRegionService.getList(new HashMap<>()));
//    }

    //查询分页列表之后对列表数据的处理
    private List<NewsInformationPageRes> handlerListAfter(List<NewsInformationDo> list) {
        List<NewsInformationPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(newsInformationDo -> {
                NewsInformationPageRes res = new NewsInformationPageRes();
                BeanUtils.copyProperties(newsInformationDo, res);
                res.setBrowseCount("1w+");
                res.setCollectCount("1w+");
                res.setFileUrl(fileService.getFilePath(newsInformationDo.getFileId()));
                result.add(res);
            });
        }
        return result;
    }

    private IPage<NewsInformationDo> pageInit(Map<String, String> map) {
        IPage<NewsInformationDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 5);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<NewsInformationDo> queryBuild(Map<String, String> map) {
        QueryWrapper<NewsInformationDo> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(map.get("keyword"))) {
//            wrapper.like("keyword", map.get("keyword"));
//        }
        return wrapper.orderByDesc("id");
    }


}
